/*
 * Copyright 2013 Krzysztof Smigielski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nilcaream.dirstore.core.common;

import com.google.common.io.ByteStreams;
import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * TODO
 * <p/>
 * Krzysztof Smigielski 7/7/13 1:22 PM
 */
class ImageTrimmer {

    public Result trim(InputStream inputStream, int size) throws IOException {
        byte[] sourceBytes = ByteStreams.toByteArray(inputStream);
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(sourceBytes));
        if (image == null) {
            return null;
        }

        Result result = new Result();
        result.width = image.getWidth();
        result.height = image.getHeight();

        if (image.getWidth() < size && image.getHeight() < size) {
            result.data = sourceBytes;
        } else {
            result.data = save(Scalr.resize(image, Scalr.Method.AUTOMATIC, size));
        }
        return result;
    }

    private byte[] save(BufferedImage image) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        // TODO original file might not be JPEG. File extensions will be mismatched.
        ImageIO.write(image, "JPEG", output);
        return output.toByteArray();
    }

    protected static class Result {
        private byte[] data;
        private int width;
        private int height;

        public byte[] getData() {
            return data;
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }
    }
}
